package com.springboot.blog.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.springboot.blog.beans.BlogClassify;
import com.springboot.blog.config.utils.R;
import com.springboot.blog.dao.ClassifyDao;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@CrossOrigin //解决跨域
@RequestMapping("/admin")
public class ClassifyController {

    @Resource
    private ClassifyDao classifyDao;

    @RequestMapping("addClassify")
    public R addClassify(String tags){
        BlogClassify blogClassify = new BlogClassify();
        blogClassify.setClassifyName(tags);
        int insert = classifyDao.insert(blogClassify);
        if (insert>0){
            return R.ok();
        }
        return R.error();
    }

    @RequestMapping("updateClassify")
    public R updateClassify(String tags, String classifyId){
        BlogClassify blogClassify = new BlogClassify();
        blogClassify.setClassifyId(Integer.parseInt(classifyId));
        blogClassify.setClassifyName(tags);
        int update = classifyDao.updateById(blogClassify);
        if (update>0){
            return R.ok();
        }
        return R.error();
    }

    @RequestMapping("deleteClassify")
    public R deleteClassify(String classifyId){
        System.out.println("========"+classifyId);
        int delete = classifyDao.deleteById(Integer.parseInt(classifyId));
        if (delete>0){
            return R.ok();
        }
        return R.error();
    }

    /**
     * 分页查询
     * @return
     */
    @RequestMapping("AllClassify")
    public String  AllClassify(String page,String limit){
        IPage<BlogClassify> pages = new Page<>(Integer.parseInt(page),Integer.parseInt(limit));
        IPage<BlogClassify> blogClassifyIPage = classifyDao.selectPage(pages, null);
        int count = classifyDao.selectCount(null);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",0);
        jsonObject.put("count",count);
        jsonObject.put("data",blogClassifyIPage);
        return jsonObject.toString();
    }
}
